<script setup>
import { ref, reactive,onMounted } from 'vue';
import { queryAllClazzApi } from '@/api/clazz';
import { queryStuList,addStudentApi,deleteStudentApi,queryStuApi,updateStudentApi,punishApi } from '@/api/stu';
import { ElMessage, ElMessageBox,ElNotification } from 'element-plus';
const searchStu=ref({
  name:'',
  degree:'',
  clazzId:''
});

const clazzList=ref([]);
const studentList=ref([
    
]);

const currentPage = ref(1) // 当前页
const pageSize = ref(10) // 每页显示条目数
const background = ref(true)  /// 是否显示背景
const total=ref(0); // 总条数

const search= async ()=>{
  const result=await queryStuList(searchStu.value.name,searchStu.value.degree,searchStu.value.clazzId
                                  ,currentPage.value,pageSize.value);
  if(result.code){
    studentList.value=result.data.rows;
    total.value=result.data.total;
  }else{
    ElMessage.error(result.msg);
  }
};

const clear=()=>{
  searchStu.value={name:'',degree:'',clazzId:''};
  search();
};

const searchAllClazz= async ()=>{
  const result=await queryAllClazzApi();
  if(result.code){
    clazzList.value=result.data;
  }
};

onMounted(()=>{
  search();
  searchAllClazz();
});

const handleSizeChange=()=>{
  search();
};

const handleCurrentChange=()=>{
  search();
};

const dialogVisible=ref(false);
const dialogTitle=ref('');

const addStudent=()=>{
  student.value={
    name: '',
    no: '',
    gender: '',
    phone: '',
    idCard: '',
    isCollege: '',
    address: '',
    degree: '',
    graduationDate: '',
    clazzId: ''
  };
  if(stuFormref.value){
    stuFormref.value.resetFields();
  }
  dialogVisible.value=true;
  dialogTitle.value='新增学员';
};

const student=ref({
    name: '',
    no: '',
    gender: '',
    phone: '',
    idCard: '',
    isCollege: '',
    address: '',
    degree: '',
    graduationDate: '',
    clazzId: ''
});

const save= async ()=>{
  if(!stuFormref.value) return ;
  stuFormref.value.validate( async (valid)=>{
    if(valid){
      let result;
      if(!student.value.id){
        result= await addStudentApi(student.value);
      }else{
        result=await updateStudentApi(student.value);
      }
      if(result.code){
        ElMessage.success("保存成功");
        dialogVisible.value=false;
        search();
      }else{
        ElMessage.error(msg);
      }
    }else{
      ElMessage.error("请输入正确的格式!");
    }
  });
};

const stuFormref=ref();
//表单校验规则
const rules = ref({
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '姓名长度应在2到10个字符之间', trigger: 'blur' }
  ],
  no:[
    { required: true, message: '请输入学号', trigger: 'blur' },
    { min: 10, max: 10, message: '学号长度为10位', trigger: 'blur'}
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  phone:[
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur'}
  ],
  idCard: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    { pattern: /^[1-9]\d{5}(19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/, message:'请输入正确的身份证号', trigger: 'blur'}
  ],
  isCollege: [
    { required: true, message: '请选择是否为 college', trigger: 'change' }
  ]
});

const ids=ref([]);
const handleSelectionChange=(selection)=>{
  ids.value=selection.map(e => e.id);
};

//删除学员
const delStudent=()=>{
  ElMessageBox.confirm(
    '你真的要删除吗?',
    'Warning',
    {
      confirmButtonText: 'OK',
      cancelButtonText: 'Cancel',
      type: 'warning',
    }
  ).then(
    async ()=>{
      if(ids.value && ids.value.length>0){
         const result= await deleteStudentApi(ids.value);
         if(result.code){
            ElNotification({
              title: 'Success',
              message: '学员删除成功',
              type: 'success',
            })
            search();//查询刷新
          }else{
            ElMessage.error(result.msg);
         }
      }else{
        ElMessage.error("请选择要删除的学员");
      }
    }
  ).catch(
    ()=>{
      ElMessage.info('删除取消');
    }
  );
};

const del=(id)=>{
  if(ids.value && ids.value.length>0){
    ids.value=[];
  }
  ids.value.push(id);
  delStudent();
};

const edit= async (id)=>{
  if(stuFormref.value){
    stuFormref.value.resetFields();
  }
  const result = await queryStuApi(id);
  if(result.code){
    student.value=result.data;
    dialogVisible.value=true;
    dialogTitle.value='编辑学员';
  }else{
    ElMessage.error(result.msg);
  }
};

const punishDialogVisible=ref(false);
const punishDialogTitle=ref('');

const Score=ref(0);
const punid=ref('');

const punish = async (id)=>{
  const result=await queryStuApi(id);
  if(result.code){
    student.value=result.data;
    Score.value=0;
    punishDialogVisible.value=true;
    punishDialogTitle.value=student.value.name;
    punid.value=student.value.id;
  }else{
    ElMessage.error(result.msg);
  }
};

const save2= async ()=>{
  if(Score.value>0){
    const result = await punishApi(punid.value,Score.value);
    if(result.code){
      ElMessage.success("保存成功");
      punishDialogVisible.value=false;
      search();
    }
  }else{
    ElMessage.error("扣除分数必须大于零!");
  }
};

</script>

<template>
  <h1>学员管理</h1>
  <!-- 学员搜索栏 -->
  <div class="container">
    <el-form :inline="true" :model="searchStu" class="demo-form-inline">
        <el-form-item label="姓名:">
          <el-input v-model="searchStu.name" placeholder="请输入姓名" clearable style="width: 150px;"/>
        </el-form-item>
        <el-form-item label="学历:">
          <el-select v-model="searchStu.degree" placeholder="请选择学历" clearable style="width: 150px;">
            <el-option label="初中" value="1" />
            <el-option label="高中" value="2" />
            <el-option label="大专" value="3" />
            <el-option label="本科" value="4" />
            <el-option label="硕士" value="5" />
            <el-option label="博士" value="6" />
          </el-select>
        </el-form-item>
        <el-form-item label="所属班级:">
          <el-select v-model="searchStu.clazzId" placeholder="请选择班级" clearable style="width: 150px;">
            <el-option v-for="clazz in clazzList" :key="clazz.id" :label="clazz.name" :value="clazz.id"/>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">查询</el-button>
          <el-button type="warning" @click="clear">清空</el-button>
        </el-form-item>
      </el-form>
   </div>
   <!-- 添加和删除学员 -->
    <div class="container">
       <el-button type="primary" @click="addStudent">+ 添加学员</el-button>
       <el-button type="danger" @click="delStudent">- 批量删除学员</el-button>
    </div>
    <!-- 学员列表 -->
     <div class="container">
      <el-table :data="studentList" border style="width: 100%" @selection-change="handleSelectionChange">
          <!-- 多选框 -->
          <el-table-column type="selection" width="55" align="center"/>
          <el-table-column prop="name" label="姓名" width="120" align="center"/>
          <el-table-column prop="no" label="学号" width="150" align="center"/>
          <el-table-column prop="clazzName" label="班级" width="150" align="center"/>
          <el-table-column prop="gender" label="性别" width="70" align="center">
            <template #default="scope">
              {{scope.row.gender==1 ? '男' : '女'}}
            </template>
          </el-table-column>
          <el-table-column prop="phone" label="联系电话" width="150" align="center"/>
          <el-table-column prop="degree" label="学历" width="80" align="center">
            <template #default="scope">
              <span v-if="scope.row.degree==1">初中</span>
              <span v-else-if="scope.row.degree==2">高中</span>
              <span v-else-if="scope.row.degree==3">大专</span>
              <span v-else-if="scope.row.degree==4">本科</span>
              <span v-else-if="scope.row.degree==5">硕士</span>
              <span v-else-if="scope.row.degree==6">博士</span>
              <span v-else="scope.row.degree=7">无</span>
            </template>
          </el-table-column>
          <el-table-column prop="violationCount" label="违纪次数" width="100" align="center"/>
          <el-table-column prop="violationScore" label="违纪分数" width="100" align="center"/>
          <el-table-column prop="updateTime" label="最后操作时间"  width="180" align="center"/>
          <el-table-column label="操作" width="200" align="center">
            <template #default="scope">
              <el-button type="primary"  @click="edit(scope.row.id)" plain class="button">编辑</el-button>
              <el-button type="warning"  @click="punish(scope.row.id)" plain class="button">违纪</el-button>
              <el-button type="danger"  @click="del(scope.row.id)" plain class="button">删除</el-button>
            </template>
          </el-table-column>
      </el-table>
     </div>
     <!-- 分页 -->
      <div class="container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[5,10,15,20,30,40,50]"
          :background="background"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          class="page"
        />
      </div>
      <!-- 对话框 -->
       <el-dialog v-model="dialogVisible" :title="dialogTitle" width="58%">
          <el-form :model="student" label-width="120px" :rules="rules" ref="stuFormref">
            <el-row :gutter="20">
              <el-col :span="12">
                  <el-form-item label="姓名:" prop="name">
                    <el-input v-model="student.name" placeholder="请输入姓名"></el-input>
                  </el-form-item>
              </el-col>
              <el-col :span="12">
                  <el-form-item label="学号:" prop="no">
                    <el-input v-model="student.no" placeholder="请输入学号"></el-input>
                  </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="性别:" prop="gender">
                  <el-select v-model="student.gender" placeholder="请选择性别">
                    <el-option label="男" value="1" />
                    <el-option label="女" value="2" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="联系电话:" prop="phone">
                  <el-input v-model="student.phone" placeholder="请输入联系电话"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="身份证号:" prop="idCard">
                  <el-input v-model="student.idCard" placeholder="请输入身份证号"></el-input>  
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="是否院校学生:" prop="isCollege">
                  <el-select v-model="student.isCollege" placeholder="请选择">
                    <el-option label="是" value="1" />
                    <el-option label="否" value="0" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="联系地址:">
                  <el-input v-model="student.address" placeholder="请输入联系地址"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="学历:">
                  <el-select v-model="student.degree" placeholder="请选择学历">
                    <el-option label="初中" value="1" />
                    <el-option label="高中" value="2" />
                    <el-option label="大专" value="3" />
                    <el-option label="本科" value="4" />
                    <el-option label="硕士" value="5" />
                    <el-option label="博士" value="6" />
                    <el-option label="无" value="7" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="院校毕业时间:">
                  <el-date-picker
                    v-model="student.graduationDate"
                    type="date"
                    placeholder="选择日期"
                    value-format="YYYY-MM-DD"
                  />
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="所属班级:">
                  <el-select v-model="student.clazzId" placeholder="请选择">
                    <el-option v-for="clazz in clazzList" :key="clazz.id" :label="clazz.name" :value="clazz.id"/>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item>
                  <el-button type="success" @click="save">保存</el-button>
               </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item>
                  <el-button type="info" @click="dialogVisible=false">取消</el-button>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
       </el-dialog>
       <!-- 处分对话框 -->
       <el-dialog v-model="punishDialogVisible" :title="punishDialogTitle" width="40%">
          <el-form :model="student" label-width="120px">
            <el-form-item label="扣除分数:">
              <el-input v-model="Score" ></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="save2">保存</el-button>
              <el-button type="info" @click="punishDialogVisible=false">取消</el-button>
            </el-form-item>
          </el-form>
       </el-dialog>
</template>

<style scoped>
.container{
  margin-top: 15px;
  margin-bottom: 0px;
}
.button{
  width: 50px;
  height: 30px;
}
</style>